/**
 * create by zhike
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.wsbank.marshall;

import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.provider.wsbank.domain.WsbankResponse;
import com.acooly.module.openapi.client.provider.wsbank.enums.WsbankGlobalCodeEnum;
import com.acooly.module.openapi.client.provider.wsbank.enums.WsbankServiceEnum;
import com.acooly.module.openapi.client.provider.wsbank.exception.WsbankApiClientProcessingException;
import com.acooly.module.openapi.client.provider.wsbank.utils.JsonMarshallor;
import com.acooly.module.openapi.client.provider.wsbank.utils.XmlUtils;
import com.acooly.module.safety.key.KeyLoadManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zhike
 */
@Service
@Slf4j
public class WsbankResponseUnmarshall extends WsbankMarshallSupport implements ApiUnmarshal<WsbankResponse, String> {

    @Resource(name = "wsbankMessageFactory")
    private MessageFactory messageFactory;

    private static JsonMarshallor jsonMarshallor = JsonMarshallor.INSTANCE;

    @Autowired
    private KeyLoadManager keyStoreLoadManager;


    @SuppressWarnings("unchecked")
    @Override
    public WsbankResponse unmarshal(String message, String serviceName) {
        try {
            log.info("响应报文:{}", message);
            WsbankGlobalCodeEnum globalCode = WsbankGlobalCodeEnum.find(message);
            if(globalCode != null) {
                throw new ApiClientException("网商银行处理接口失败，错误码code["+message+"],错误码说明："+globalCode.getMessage());
            }
            // 验签
            doVerifySign(message);
            log.info("验签成功");
            return doUnmarshall(message, serviceName);
        } catch (Exception e) {
            throw new WsbankApiClientProcessingException(e.getMessage());
        }
    }

    protected WsbankResponse doUnmarshall(String respXml, String serviceName) {
        WsbankResponse response = (WsbankResponse) messageFactory.getResponse(WsbankServiceEnum.find(serviceName).getCode());
        response = XmlUtils.toBean(respXml,response.getClass());
        response.setService(WsbankServiceEnum.find(serviceName).getCode());
        return response;
    }

    public void setMessageFactory(MessageFactory messageFactory) {
        this.messageFactory = messageFactory;
    }


}
